package com.qf.blog.controller.web;

import com.alibaba.fastjson.JSON;
import com.qf.blog.core.servlet.BaseServlet;
import com.qf.blog.entity.CommentEntity;
import com.qf.blog.entity.InvitataionEntity;
import com.qf.blog.entity.UserEntity;
import com.qf.blog.service.ICommentService;
import com.qf.blog.service.IInvitataionService;
import com.qf.blog.service.IUserService;
import com.qf.blog.service.impl.CommentServiceImpl;
import com.qf.blog.service.impl.InvitataionServiceImpl;
import com.qf.blog.service.impl.UserServiceImpl;
import com.qf.blog.vo.CommentVo;
import jdk.nashorn.internal.ir.CallNode;
import org.springframework.context.ApplicationContext;

import javax.servlet.annotation.WebServlet;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/invitataionServlet/*")
public class InvitataionServlet extends BaseServlet {

    private IInvitataionService invitataionService;

    private IUserService userService;

    private ICommentService commentService;

    @Override
    public void myInit() {
        ApplicationContext ctx = (ApplicationContext) this.req.getServletContext().getAttribute("spring");
        invitataionService = ctx.getBean(IInvitataionService.class);
        commentService = ctx.getBean(ICommentService.class);
        userService = ctx.getBean(IUserService.class);
    }


    public String publish() throws Exception {

        // 1.获取登录用户
        UserEntity loginUser = (UserEntity) req.getSession().getAttribute("loginUser");
        if (loginUser == null) {
            return outJson(100, "超时了，请重新登录");
        }

        // 2.获取前端传递的数据
        String s = req.getReader().readLine();
        InvitataionEntity invitataionEntity = JSON.parseObject(s, InvitataionEntity.class);

        // 3.封装用户
        invitataionEntity.setUserId(loginUser.getId());
        boolean save = invitataionService.save(invitataionEntity);

        return outJson(save);
    }

    public void info() throws Exception {
        String id = req.getParameter("id");

        // 1.查询帖子
        InvitataionEntity invitataionEntity = invitataionService.byId(Integer.parseInt(id));

        // 2.查询作者
        Integer userId = invitataionEntity.getUserId();
        UserEntity userEntity = userService.byId(userId);

        // 3.查询帖子的评论
        List<CommentVo> commentEntityList = commentService.commentListByInvitataionId(invitataionEntity.getId());

        // 4.把帖子的数据和作者的数据放到map中
        Map<String, Object> map = new HashMap<>();
        map.put("topic", invitataionEntity);
        map.put("user", userEntity);
        map.put("commentVoList", commentEntityList);

        // 5.跳转到视图
        outView("view/site/discuss-detail", map);
    }
}
